import api from "@/utils";
import { provide, ref, UnwrapRef } from "vue";
import { TableField, TableUrl } from "@/models/TableSetting";
import { ElMessage } from "element-plus";

export default function TableData(
  props: {
    url: TableUrl;
    tableFieldList: Array<TableField>;
    submitForm: Record<string, unknown>;
    searchForm: Record<string, unknown>;
  },
  emit: {
    (
      e: "data-format",
      columnName: string,
      cellValue: string,
      callback: (value: string) => void
    ): void;
    (
      e: "set-form-init-value",
      formType: string,
      row: Record<string, unknown>
    ): void;
  }
) {
  const lastSearchUrl = ref("");
  const lastSearchReceipts = ref({} as Record<string, unknown>);

  // 表单数据
  const tableData = ref([] as Array<Record<string, unknown>>);

  // 获取表数据
  const getRecord = async (
    url?: string,
    receipts?: Record<string, unknown>
  ) => {
    if (url === null || url === undefined) {
      url = lastSearchUrl.value;
    }
    if (receipts === null || receipts === undefined) {
      receipts = lastSearchReceipts.value;
    }
    await api.http
      .postJson(url, receipts)
      .then((res) => {
        // console.log(url);
        // console.log(receipts);
        // console.log(res);
        tableData.value = res.data;
        lastSearchUrl.value = url as string;
        lastSearchReceipts.value = receipts as Record<string, unknown>;
      })
      .catch((err) => {
        console.log(err);
      });
  };
  // provide 中一定不能加()，否则将直接执行方法，而不执行provide.
  provide("refreshData", getRecord);

  // 数据规整
  // 对于Object类型，不能直接用, 如果是any object, 使用 Record<string, unknown>作为其申明.
  const dataFormat = (
    row: UnwrapRef<never>,
    column: UnwrapRef<Record<string, string>>,
    cellValue: UnwrapRef<string>
  ) => {
    emit("data-format", column.property, cellValue, (value: string) => {
      cellValue = value;
    });
    // 正则表达式判断是否是日期, 日期格式为 2021-12-26T06:51:12.000+00:00,此前父组件emit事件处理后的结果为yyyy年MM月dd日，有汉字，不会符合这个规范
    const regDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}\+\d{2}:\d{2}$/;
    const isDate = regDate.test(cellValue);
    if (isDate) {
      const date = new Date(cellValue);
      return api.formatDate(date, "yyyy年MM月dd日 hh时mm分ss秒");
    }
    return cellValue;
  };

  // 基本搜索
  const basicSearch = (field: string, content: string | number) => {
    if (field === "") {
      ElMessage.warning("请勾选要筛选的项");
    } else if (content === "") {
      ElMessage.warning("请输入搜索内容！");
    } else {
      getRecord(props.url.refreshUrl + "/" + field + "/" + content).then();
    }
  };
  provide("basicSearch", basicSearch);

  const resetSearch = () => {
    getRecord(props.url.refreshUrl).then();
  };
  provide("resetSearch", resetSearch);

  // 获取组合数据搜索
  const search = async () => {
    // //向后端发送搜索请求
    await api.http
      .postJson(props.url?.searchUrl, props.searchForm)
      .then((res) => {
        // console.log(props.searchForm);
        // console.log(res);
        tableData.value = res.data;
        lastSearchUrl.value = props.url.searchUrl as string;
        lastSearchReceipts.value = props.searchForm as Record<string, unknown>;
      })
      .catch((err) => {
        console.log(err);
      });
  };
  provide("search", search);

  return {
    tableData,
    getRecord,
    dataFormat,
  };
}
